package com.gw.booking.service;

import com.gw.booking.util.TemplateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.util.Map;
import java.util.Properties;

@Service
public class HqlService {
    private static Logger logger = LoggerFactory.getLogger(HqlService.class);

    @Value("${config.hqlFolder}")
    private String configPath;
    private static Properties sqlCache = new Properties();

    public HqlService() {
    }

    private void load() {
        if (!sqlCache.isEmpty()) {
            return;
        }

        String classpath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        configPath = configPath.replace("classpath:", classpath);

        File file = new File(configPath);
        File[] files = file.listFiles();

        for (File config : files) {
            loadSqls(config);
        }
    }

    private void loadSqls(File config) {
        try {
            sqlCache.load(new FileInputStream(config));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getSql(String name, Map<String, ?> params) {
        load();

        if (!sqlCache.containsKey(name)) {
            logger.error("Sql不存在。key:" + name);
        }
        return parse(sqlCache.getProperty(name), params);
    }

    /**
     * 取得计数sql
     */
    public String getSqlCount(String name, Map<String, ?> params, boolean isNativeSql) {
        String sql = getSql(name, params);
        String sqlCount = "";
        int orderIndex = sql.lastIndexOf(" order by ");
        orderIndex = orderIndex > 0 ? orderIndex : sql.length();

        if (isNativeSql) {
            sqlCount = "select count(*) from (" + sql.substring(0, orderIndex) + ") tmp_count_t";
        } else {
            sqlCount = "select count(*) " + sql.substring(sql.indexOf(" from "), orderIndex);
        }

        return sqlCount;
    }

    private static String parse(String sql, Map<String, ?> params) {
        if (params == null) {
            return sql;
        } else {
            String statement = TemplateUtil.replaceTemplate(sql, params);
            statement = TemplateUtil.removeOptionalFrag(statement, params);
            if (logger.isDebugEnabled()) {
                logger.debug("Return=" + statement);
            }

            return statement;
        }
    }
}
